package com.sl.designmodekt

import java.io.Serializable
import kotlin.math.min

/**
 * author： suliang
 * 2022/11/28 15:43
 * describe : Kotlin的单例模式实现
 * https://cloud.tencent.com/developer/article/1587347
 */
/*
饿汉式的单例模式
object Singleton : Serializable  {
    fun doSomething(){
        println("do something")
    }
    //防止单例对象在反序列化时重新生成对象
    private fun readResolve():Any{
        return Singleton
    }
}*/

//懒汉式，方法加锁的懒汉式，线程安全
/*class Singleton private constructor() : Serializable {
    companion object {
        private var mInstance : Singleton ? = null

        @JvmStatic
        @Synchronized       //添加同步锁
        fun getInstance() : Singleton {
            if (null == mInstance){
                mInstance = Singleton()
            }
            return requireNotNull(mInstance)
        }
    }
    //防止单例对象在反序列化时生成新的对象
    private fun readResolve():Any{
        return Singleton.getInstance()
    }

    fun doSomething(){
        println("do something")
    }
    //kotlin调用
    fun test(){
        Singleton.getInstance().doSomething()
    }
}*/

//懒汉式： 线程不安全
/*class Singleton private constructor() {
    companion object{
        private var mInstance : Singleton? = null
        get() {
            return field?: Singleton()
        }
        @JvmStatic
        fun getInstance() : Singleton{
            return requireNotNull(mInstance)
        }
    }
    fun doSomething(){
        println("do something")
    }
}*/

//懒汉式： DCL 线程安全
/*
class Singleton private constructor(){
    companion object{
        //使用lazy属性代理，并指定LazyThreadSafetyMode为synchronized模式保证线程安全
        @JvmStatic
        val instance : Singleton by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
            Singleton()
        }
    }
    fun doSomething(){
        println("do something")
    }
}
//调用
fun test(){
    Singleton.instance.doSomething()
}
*/

//静态内部类实现单例
/*
class Singleton private constructor() {
    companion object{
        @JvmStatic
        fun getInstance(): Singleton {
            return SingletonHolder.mInstance
        }
    }
    fun doSomething(){
        println("do something")
    }
    //静态内部类
    private object SingletonHolder {
        val mInstance = Singleton()
    }
}
*/

//枚举实现单例
enum class Singleton {
    INSTANCE ;
    fun doSomething(){
        println("do something")
    }
}